package com.service.share.impl;

import com.dao.share.ExcelMapper;
import com.entity.Answer;
import com.entity.share.Excel;
import com.service.share.ExcelService;
import com.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExcelServiceImpl implements ExcelService {
    private String path = ClassUtils.getDefaultClassLoader().getResource("static/").getPath();;
    private String excelPath = "/patient/excel/";
    private Workbook wb;
    private Sheet sheet;
    private Row row;
    private String[] name = {"inner", "panoramic", "head", "deformity1", "deformity2", "deformity3", "deformity4", "data", "existing", "diagnose"};
    @Autowired
    private ExcelMapper excelMapper;

    public Object viewExcel(String excelPath) {
        System.out.println(excelPath);
        Answer answer = new Answer();
        String filepath = excelPath;
       Map<String, List<List<String>>> data = new HashMap<String, List<List<String>>>();
       String json = new String("{");
        if (filepath == null) {
            return null;
        }
        String ext = filepath.substring(filepath.lastIndexOf("."));
        try {
            InputStream is = new FileInputStream(filepath);
            if (".xls".equals(ext)) {
                wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(ext)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            answer.setCode(0);
            answer.setError("未找到文件");
            return answer;

        } catch (IOException e) {
            e.printStackTrace();
            answer.setCode(0);
            answer.setError("文件流错误");
            return answer;
        }
        if (wb == null) {
            answer.setCode(0);
            answer.setError("文件格式错误");
            return answer;
        }
        int sheetnum = wb.getNumberOfSheets();
        for (int j = 0; j < sheetnum; j++) {
            sheet = wb.getSheetAt(j);
            row = sheet.getRow(0);
//        // 总列数
            int colNum = row.getPhysicalNumberOfCells();
            // 得到总行数
            int rowNum = sheet.getLastRowNum();


            Map<String, List<List<String>>> map = new HashMap<>();
            List<List<String>> lists = new ArrayList<>();
            for (int i = 0; i <= rowNum; i++) {

                List<String> list = new ArrayList<>();
                row = sheet.getRow(i);

                for (int k = 0; k < colNum; k++) {
                    //System.out.println(row.getCell(k));
                    list.add(String.valueOf(row.getCell(k)));
                }
                lists.add(list);
            }
            if (j == 0){
                json = json + "\""+name[j]+"\":"+ JSONArray.fromObject(lists);
                continue;
            }
              json = json + ",\""+name[j]+"\":"+ JSONArray.fromObject(lists);

        }
        json  = json +"}";
        System.out.println(json);
        JSONObject array = JSONObject.fromObject(json);
        answer.setCode(1);
        answer.setData(array.toString());
        return answer;
    }

    public Object addExcel(List<MultipartFile> files, int patientID){
      Answer answer = (Answer)Util.uploadFiles(files, path + excelPath + patientID + "/");
      if (answer != null){
          return answer;
      }

      answer = (Answer)this.viewExcel(path + excelPath + patientID + "/"+files.get(0).getOriginalFilename());
      if (answer.getCode() == 0){
          return  answer;
      }
      Excel excel = new Excel();
      excel.setPatientID(patientID);
      excel.setConclusion((String) answer.getData());
      try {
          //判断是否上传过
          if (excelMapper.queryExcel(patientID) == null){
              //添加到数据库，并判断是否添加成功
              if (excelMapper.addExcel(excel) == 0){
                  answer = new Answer();
                  answer.setCode(0);
                  answer.setError("上传失败！");
                  return  answer;
              }
          }else {
              //修改数据，并判断是否修改成功
              if (excelMapper.updateExcel(excel) == 0){
                  answer = new Answer();
                  answer.setCode(0);
                  answer.setError("上传失败！");
                  return  answer;
              }
          }

      }catch (Exception e){
          e.printStackTrace();
          answer = new Answer();
          answer.setCode(0);
          answer.setError("上传失败！");
          return  answer;
      }

        answer = new Answer();
        answer.setCode(1);
        return answer;
    }
    public Object updataNegativeText(Integer patientID,String key,String value){
        Answer answer = new Answer();
        try {
            if (excelMapper.updataNegativeText(patientID,key,value) !=0 ){
                answer.setCode(1);
            }else {
                answer.setCode(0);
                answer.setError("修改失败！");
                return answer;
            }
        }catch (Exception e){
            e.printStackTrace();
            answer.setCode(0);
            answer.setError("修改失败！");
            return answer;
        }
        return answer;
    }
}
